import time

from system.models import AllMenu, MenuLevel, AllLevel, User, LevelMenu

#接口
from django.http import HttpResponse,JsonResponse
from django.views.decorators.csrf import csrf_exempt

from system.views import SUCCESS_CODE,ERR_CODE,ERR_TIMEOUT,SUCCESS_MESSAGE,ERR_MESSAGE


# 添加菜单
@csrf_exempt
def addMenu(request):
    dic = {}
    if request.method == "POST":
        name = request.POST.get('name')
        pid = request.POST.get('pid')
        path = request.POST.get('path')
        if name:
            menu = AllMenu.objects.filter(name=name)
            if menu:
                dic['code'] = ERR_CODE
                dic['message'] = '该菜单已存在'
            else:
                menu = AllMenu()
                menu.name = name
                menu.pid = pid
                menu.path = path
                menu.gmt_create = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
                menu.gmt_modify = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
                menu.save()

                dic['code'] = SUCCESS_CODE
                dic['message'] = '添加成功'
        else:
            dic['code'] = ERR_CODE
            dic['message'] = '数值不能为空'
    else:
        dic['code'] = ERR_CODE
        dic['message'] = ERR_MESSAGE
    return JsonResponse(dic, json_dumps_params={'ensure_ascii': False})


# 删除菜单
@csrf_exempt
def deleteMenu(request):
    dic = {}
    if request.method == "POST":
        id = request.POST.get('id')
        menu = AllMenu.objects.filter(id=id)
        if menu:
            menu[0].delete()
            dic['code'] = SUCCESS_CODE
            dic['message'] = SUCCESS_MESSAGE
        else:
            dic['code'] = ERR_CODE
            dic['message'] = '菜单不存在'
    else:
        dic['code'] = ERR_CODE
        dic['message'] = ERR_MESSAGE
    return JsonResponse(dic, json_dumps_params={'ensure_ascii': False})


# 获取菜单
@csrf_exempt
def MenuInfo(request):
    dic = {}
    if request.method == "POST":
        info = AllMenu.objects.all()
        if info:
            menuList = []
            for i in info:
                data = {}
                data['id'] = i.id
                data['name'] = i.name
                data['pid'] = i.pid
                data['path'] = i.path
                menuList.append(data)
            dic['code'] = SUCCESS_CODE
            dic['message'] = SUCCESS_MESSAGE
            isAll = request.POST.get('isAll')
            if isAll == 1 or isAll == '1':
                dic['data'] = {
                    'menuList': menuList,
                    'size': len(menuList)
                }
            else:
                page = int(request.POST.get('page'))
                pageSize = int(request.POST.get('pageSize'))
                minSize = (page - 1) * pageSize
                maxSize = page * pageSize
                if maxSize >= len(menuList):
                    dic['data'] = {
                        'menuList': menuList[minSize:],
                        'size': len(menuList)
                    }
                else:
                    dic['data'] = {
                        'menuList': menuList[minSize:maxSize],
                        'size': len(menuList)
                    }
        else:
            dic['code'] = SUCCESS_CODE
            dic['message'] = '暂时没有菜单'
    else:
        dic['code'] = ERR_CODE
        dic['message'] = ERR_MESSAGE
    return JsonResponse(dic, json_dumps_params={'ensure_ascii': False})

# 获取页面信息
@csrf_exempt
def getMenu(request):
    dic = {}
    if request.method == 'POST':
        menu_id = request.POST.get('pageId')
        menu = AllMenu.objects.filter(id=menu_id)
        if menu:
            dic['data'] = {
                'id': menu[0].id,
                'name': menu[0].name,
                'pid': menu[0].pid,
                'path': menu[0].path
            }
            dic['code'] = SUCCESS_CODE
            dic['message'] = SUCCESS_MESSAGE

        else:
            dic['code'] = ERR_CODE
            dic['message'] = '该页面不存在'
    else:
        dic['code'] = ERR_CODE
        dic['message'] = ERR_MESSAGE
    return JsonResponse(dic, json_dumps_params={'ensure_ascii': False})

# 修改菜单
@csrf_exempt
def editMenu(request):
    dic = {}
    if request.method == 'POST':
        menu_id = request.POST.get('id')
        name = request.POST.get('name')
        pid = request.POST.get('pid')
        path = request.POST.get('path')

        actionsUser = request.POST.get('actionsUser')
        if User.objects.filter(username=actionsUser)[0].level == '3':
            menu = AllMenu.objects.filter(id=menu_id)[0]
            if menu:
                menu.name = name
                menu.pid = pid
                menu.path = path
                menu.gmt_modify = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
                menu.save()

                dic['code'] = SUCCESS_CODE
                dic['message'] = SUCCESS_MESSAGE
            else:
                dic['code'] = ERR_CODE
                dic['message'] = '找不到该菜单'
        else:
            dic['code'] = ERR_CODE
            dic['message'] = '没有权限'
    else:
        dic['code'] = ERR_CODE
        dic['message'] = ERR_MESSAGE
    return JsonResponse(dic, json_dumps_params={'ensure_ascii': False})


# 添加角色菜单
@csrf_exempt
def addMenuLevel(request):
    dic = {}
    if request.method == "GET":
        level_id = int(request.GET.get('level_id'))
        menu_id = int(request.GET.get('menu_id'))
        level_item = AllLevel.objects.filter(id=level_id)
        menu_item = AllMenu.objects.filter(id=menu_id)
        if level_item and menu_item:
            menu = MenuLevel.objects.filter(level_id=level_id).filter(menu_id=menu_id)
            if menu:
                dic['code'] = ERR_CODE
                dic['message'] = '该菜单已存在'
            else:
                menu = MenuLevel()
                menu.level_id = level_id
                menu.menu_id = menu_id
                menu.pid = menu_item[0].pid
                menu.name = menu_item[0].name
                menu.path = menu_item[0].path
                menu.gmt_create = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
                menu.gmt_modify = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
                menu.save()

                dic['code'] = SUCCESS_CODE
                dic['message'] = '添加成功'
        else:
            dic['code'] = ERR_CODE
            dic['message'] = '数值不能为空'
    else:
        dic['code'] = ERR_CODE
        dic['message'] = ERR_MESSAGE
    return JsonResponse(dic, json_dumps_params={'ensure_ascii': False})


# 删除菜单
@csrf_exempt
def deleteMenuLevel(request):
    dic = {}
    if request.method == "GET":
        id = request.GET.get('id')
        menu = MenuLevel.objects.filter(id=id)
        if menu:
            menu[0].delete()
            dic['code'] = SUCCESS_CODE
            dic['message'] = SUCCESS_MESSAGE
        else:
            dic['code'] = ERR_CODE
            dic['message'] = '菜单不存在'
    else:
        dic['code'] = ERR_CODE
        dic['message'] = ERR_MESSAGE
    return JsonResponse(dic, json_dumps_params={'ensure_ascii': False})


# 获取菜单
@csrf_exempt
def MenuLevelInfo(request):
    dic = {}
    if request.method == "GET":
        level_id = request.GET.get('level_id')
        if level_id:
            info = MenuLevel.objects.filter(level_id=level_id)
        else:
            info = MenuLevel.objects.all()
            # info = []
        if info:
            menuList = []
            for i in info:
                if i.pid=='0':
                    data = {}
                    data['id'] = i.id
                    data['menu_id'] = i.menu_id
                    data['name'] = i.name
                    data['path'] = i.path
                    data['pid'] = i.pid
                    item_info = info.filter(pid=i.menu_id)
                    item_list = []
                    item_list.append({
                        'id': i.id, 'menu_id': i.menu_id, 'name': i.name, 'path': i.path,
                        'pid': i.pid
                    })
                    if item_info:
                        for j in item_info:
                            item_data = {}
                            item_data['id'] = j.id
                            item_data['menu_id'] = j.menu_id
                            item_data['name'] = j.name
                            item_data['path'] = j.path
                            item_data['pid'] = j.pid
                            item_list.append(item_data)
                    data['child'] = item_list
                    menuList.append(data)
            dic['code'] = SUCCESS_CODE
            dic['message'] = SUCCESS_MESSAGE
            dic['data'] = {
                'menuList': menuList
            }
        else:
            dic['code'] = SUCCESS_CODE
            dic['message'] = '暂时没有菜单'
    else:
        dic['code'] = ERR_CODE
        dic['message'] = ERR_MESSAGE
    return JsonResponse(dic, json_dumps_params={'ensure_ascii': False})


# 修改菜单
@csrf_exempt
def editMenuLevel(request):
    dic = {}
    if request.method == 'GET':
        menu_level_id = request.GET.get('id')
        menu = MenuLevel.objects.filter(id=menu_level_id)[0]
        if menu:
            level_id = int(request.GET.get('level_id'))
            menu_id = int(request.GET.get('menu_id'))
            level_item = AllLevel.objects.filter(id=level_id)
            menu_item = AllMenu.objects.filter(id=menu_id)
            if level_item and menu_item:
                menu.level_id = level_id
                menu.menu_id = menu_id
                menu.pid = menu_item[0].pid
                menu.name = menu_item[0].name
                menu.path = menu_item[0].path
                menu.gmt_modify = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
                menu.save()

                dic['code'] = SUCCESS_CODE
                dic['message'] = SUCCESS_MESSAGE
            else:
                dic['code'] = ERR_CODE
                dic['message'] = '找不到该菜单或角色等级'
        else:
            dic['code'] = ERR_CODE
            dic['message'] = '找不到该菜单'
    else:
        dic['code'] = ERR_CODE
        dic['message'] = ERR_MESSAGE
    return JsonResponse(dic, json_dumps_params={'ensure_ascii': False})


"""获取菜单"""
@csrf_exempt
def LevelMenuInfo(request):
    dic = {}
    if request.method == 'POST':
        username = request.POST.get('username')
        level = User.objects.filter(username=username)[0].level
        menu = LevelMenu.objects.filter(level=level)
        menuList = []
        for i in menu:
            if i.menu.pid == '0' or i.menu.pid == 0:
                item = {
                    'id': i.menu.id,
                    'pid': i.menu.pid,
                    'name': i.menu.name,
                    'path': i.menu.path,
                    'child': [{
                        'id': i.menu.id,
                        'pid': i.menu.pid,
                        'name': i.menu.name,
                        'path': i.menu.path,
                    }]
                }
                item_menu = menu.filter(menu__pid=i.menu.id)
                if item_menu:
                    for j in item_menu:
                        j_item = {
                            'id': j.menu.id,
                            'pid': j.menu.pid,
                            'name': j.menu.name,
                            'path': j.menu.path
                        }
                        item['child'].append(j_item)
                menuList.append(item)
        dic['code'] = SUCCESS_CODE
        dic['message'] = SUCCESS_MESSAGE
        dic['data'] = {
            'menuList': menuList
        }
    else:
        dic['code'] = ERR_CODE
        dic['message'] = ERR_MESSAGE
    return JsonResponse(dic, json_dumps_params={'ensure_ascii': False})

"""获取配置角色菜单数据"""
@csrf_exempt
def GetLevelMenu(request):
    dic = {}
    if request.method == 'POST':
        level = request.POST.get('level')
        if level != '' or level != 0:
            menu = LevelMenu.objects.filter(level=level)
            menuList = []
            for i in menu:
                menuList.append(i.menu.id)
            dic['code'] = SUCCESS_CODE
            dic['message'] = SUCCESS_MESSAGE
            dic['data'] = {
                'menuList': menuList
            }
        else:
            dic['code'] = ERR_CODE
            dic['message'] = '没有改角色权限'
    else:
        dic['code'] = ERR_CODE
        dic['message'] = ERR_MESSAGE
    return JsonResponse(dic, json_dumps_params={'ensure_ascii': False})

"""添加角色菜单"""
@csrf_exempt
def AddLevelMenu(request):
    dic = {}
    if request.method == "POST":
        level_id = request.POST.get('level_id')
        menu_id = request.POST.get('menu_id')
        levelMenu = LevelMenu.objects.filter(level=level_id).filter(menu=menu_id)
        if levelMenu:
            dic['code'] = ERR_CODE
            dic['message'] = '该角色菜单已存在'
        else:
            levelMenu = LevelMenu()
            levelMenu.menu = AllMenu.objects.filter(id=menu_id)[0]
            levelMenu.level = AllLevel.objects.filter(id=level_id)[0]
            levelMenu.gmt_create = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            levelMenu.gmt_modify = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            levelMenu.save()

            dic['code'] = SUCCESS_CODE
            dic['message'] = SUCCESS_MESSAGE
    else:
        dic['code'] = ERR_CODE
        dic['message'] = ERR_MESSAGE
    return JsonResponse(dic, json_dumps_params={'ensure_ascii': False})

"""删除角色菜单"""
@csrf_exempt
def DeleteLevelMenu(request):
    dic = {}
    if request.method == "POST":
        level_id = request.POST.get('level_id')
        menu_id = request.POST.get('menu_id')
        levelMenu = LevelMenu.objects.filter(level=level_id).filter(menu=menu_id)
        if levelMenu:
            levelMenu[0].delete()
            dic['code'] = SUCCESS_CODE
            dic['message'] = SUCCESS_MESSAGE
        else:
            dic['code'] = ERR_CODE
            dic['message'] = '该角色菜单不存在'
    else:
        dic['code'] = ERR_CODE
        dic['message'] = ERR_MESSAGE
    return JsonResponse(dic, json_dumps_params={'ensure_ascii': False})